package kursynbp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class ExchangeDAO extends Exchange {

	public ExchangeDAO(String code) {
		super(code);
	}
	
	public static Integer persist(Connection connection, Exchange ex) {
		
		try {
			// Connection connection = DBConnectionFactory.getInstance().getConnection();

			String q1 = "SELECT id FROM currency WHERE code = \'" + ex.getCode() + "\'";
			Statement st1 = connection.createStatement();
			ResultSet res1 = st1.executeQuery(q1);
			Integer currency_id;
			if (res1.next()) {
				currency_id = res1.getInt("id");
			} else {
				String q2 = "INSERT INTO currency (code) VALUES (\'" + ex.getCode() + "\')";
				PreparedStatement prep1 = connection.prepareStatement(q2);
				prep1.executeUpdate();
				
				Statement st2 = connection.createStatement();
				ResultSet res2 = st2.executeQuery(q1);
				
				res2.next();
				currency_id = res2.getInt("id");
			}
			
			return currency_id;
		} catch(Exception e) {
			throw new DBPersistorException("Could not persist currency object");
		}
	}

	public static String find(Connection connection, Integer id) {
		try {
			// Connection connection = DBConnectionFactory.getInstance().getConnection();

			String query = "SELECT code FROM currency WHERE id = " + id;
			Statement st = connection.createStatement();
			ResultSet rs = st.executeQuery(query);
			if (rs.next()) {
				return rs.getString("code");
			}
			return null;
		} catch (Exception e) {
			throw new DBPersistorException("Could not retrieve currency from database.");
		}
	}
	
}
